<?php

namespace App\Listeners;

use App\Events\ProfitShare;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Models\ProfitSharingAccount;
use App\Contracts\WxProfitSharing;
use App\Models\ProfitSharingReceiver;
use Illuminate\Support\Facades\Log;

class WxProfitShare
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ProfitShare  $event
     * @return void
     */
    public function handle(ProfitShare $event)
    {
        $notifyData = $event->notifyData;
        $subAppId = isset($notifyData['sub_appid']) ? $notifyData['sub_appid'] : $notifyData['appid'];
        $subMchId = isset($notifyData['sub_mch_id']) ? $notifyData['sub_mch_id'] : $notifyData['mch_id'];

        // 获取分账接收方
        $wxProfitSharingAccount = ProfitSharingAccount::where('sub_appid', $subAppId)->where('sub_mchid', $subMchId)->first();
        Log::info('WxProfitShare Listener------begin');
        Log::info($wxProfitSharingAccount);
        Log::info($wxProfitSharingAccount->id);

        if(!empty($wxProfitSharingAccount))
        {
            $wxProfitSharingReceivers = ProfitSharingReceiver::where('profit_sharing_account_id',$wxProfitSharingAccount->id)->get();
            Log::info($wxProfitSharingReceivers);
            Log::info('WxProfitShare Listener------end');

            if(!empty($wxProfitSharingReceivers))
            {
                // 组合分账接收方
                $receivers = array();

                // 组合分账接收方
                foreach ($wxProfitSharingReceivers as $wxProfitSharingReceiver)
                {
                    $accountsTmp = array();
                    $accountsTmp['type'] = $wxProfitSharingReceiver['type'];
                    $accountsTmp['account'] = $wxProfitSharingReceiver['account'];
                    $accountsTmp['amount'] = intval(bcmul(bcdiv($wxProfitSharingReceiver['amount'],100,2), $notifyData['total_fee']));// 单位：分。且是整型，不能是字符串
                    $accountsTmp['description'] = $wxProfitSharingReceiver['desc'];

                    // 组合分账接收方和分账标志
                    $receiverTmp = array();
                    $receiverTmp['profit_sharing_order_id'] = $notifyData['out_trade_no'].'_'.$wxProfitSharingReceiver['id'];
                    $receiverTmp['accounts'] = array($accountsTmp);
                    $receivers[] = $receiverTmp;
                }

                $channel = $subAppId.'_'.$subMchId;// 渠道标志
                $transId = $notifyData['transaction_id'];// 微信支付商户号

                $profitSharing = new WxProfitSharing();
                $profitSharing->req($channel, $transId, $subAppId, $subMchId, $receivers);
            }
        }
    }


}
